/**
 * 统一API响应处理工具
 */

/**
 * 检查响应是否成功
 * @param {Object} response - API响应对象
 * @returns {boolean} 是否成功
 */
export const isResponseSuccess = (response) => {
  return response && response.hasOwnProperty('code') && response.code === 0
}

/**
 * 获取响应数据
 * @param {Object} response - API响应对象
 * @returns {*} 响应数据
 */
export const getResponseData = (response) => {
  return response?.data || null
}

/**
 * 获取响应错误信息
 * @param {Object} response - API响应对象
 * @returns {string} 错误信息
 */
export const getResponseErrorMessage = (response) => {
  return response?.message || '未知错误'
}

/**
 * 处理API响应
 * @param {Object} response - API响应对象
 * @returns {*} 处理后的数据或抛出错误
 */
export const handleResponse = (response) => {
  if (isResponseSuccess(response)) {
    return getResponseData(response)
  } else {
    throw new Error(getResponseErrorMessage(response))
  }
}

export default {
  isResponseSuccess,
  getResponseData,
  getResponseErrorMessage,
  handleResponse
}